﻿using DevComponents.DotNetBar;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using UniRlv.COL;
using UniRlv.UI.Main.BasicInfo;
using UniRlv.UI.Main.WarerHourseIn;
using UniRlv.UI.Main.Widget;
using UniRlv.Utility;
using UniRlv.Utility.Extend;

namespace UniRlv.UI.Main
{
    public partial class FrmMain : OfficeForm
    {
        FrmBase frmCurrent = null;
        bool bInit = false;
        //FrmCriticalError frmError = new FrmCriticalError();
        List<string> msgErr = new List<string>();
        int numSaveTimeSpan = 5;//自动保存数据时间间隔，默认一分钟    //2020-3-25,单位改为秒，默认5秒
        int numLogCLrPeriod = 90;
        int numProccessCLrPeriod = 3;
        int ticksSystem = 0;//系统时钟数量
        int lastSaveQty = 0;

        string tempDir, expDir, logDir;

        private static FrmMain _instance = null;

        public EventHandler<CodeSaveEventArg> CodeSaveEvent;
        public EventHandler<EventArgs> CodeRefreshEvent;//异常处理时触发
        public EventHandler<CodePrintEventArg> CodePrintEvent;//打印触发
        public EventHandler<EventArgs> CriticalError;//出现重要错误
        public DateTime lastRltCodeLoadTime = DateTime.MinValue;

        public FrmMain()
        {
            InitializeComponent();
        }

        public static FrmMain GetInstance()
        {
            if (_instance == null)
            {
                _instance = new FrmMain();
            }

            return _instance;
        }

        private void FrmMain_FormClosed(object sender, FormClosedEventArgs e)
        {
        }

        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (bInit)
            {//确认退是否出
                if (PublicObject.CurTask!=null)
                {
                    if (PublicObject.CurTask.state == (int)task_state.TS_RUN)
                    {
                        MessageBox.Show(this, "先暂停生产任务！", "提示");
                        e.Cancel = true;
                        return;
                    }
                    else if (PublicObject.arrCode1.Count>0)
                    {
                        if (MessageBox.Show(this, "任务尚未审核保存，继续退出将丢失扫描进度，确定退出？", "警告", MessageBoxButtons.OKCancel, 
                            MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1) == System.Windows.Forms.DialogResult.OK)
                        {

                            

                            if (!WorkSpace.GetInstance().Quit())
                            {
                                MessageBox.Show(this, "暂时无法暂停任务：" + WorkSpace.GetInstance().ErrorString, "提示");
                                e.Cancel = true;
                                return;
                            }
                            else
                            {
                                timer1.Stop();
                                //frmError.Close();
                            }
                        }
                        else
                        {
                            e.Cancel = true;
                            return;
                        }
                    }

                }
                else
                {
                    if (!WorkSpace.GetInstance().Quit())
                    {
                        MessageBox.Show(this, "暂时无法暂停任务：" + WorkSpace.GetInstance().ErrorString, "提示");
                        e.Cancel = true;
                        return;
                    }
                }

            }
            else
            {

            }
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            string msg = string.Empty;
#region 初始化工作空间

            WorkSpace.GetInstance().TaskStartEvent += new EventHandler<EventArgs>((s1, s2) => 
            {
                CallCtrlWithThreadSafety.SetText(lbTYM, PublicObject.CurTask.tym, this);
                CallCtrlWithThreadSafety.SetText(lbPZWH, PublicObject.CurTask.pzwh, this);
                CallCtrlWithThreadSafety.SetText(lbBatch, PublicObject.CurTask.batch, this);
                CallCtrlWithThreadSafety.SetText(lbCreator, PublicObject.CurTask.creator, this);
                CallCtrlWithThreadSafety.SetText(lbLine, PublicObject.CurLine.name, this);

                CallCtrlWithThreadSafety.SetText(lbTaskID, PublicObject.CurTask.ID.ToString(), this);
                CallCtrlWithThreadSafety.SetText(lbGG, PublicObject.CurTask.gg, this);
                CallCtrlWithThreadSafety.SetText(lbRatio, PublicObject.CurTask.tagRatio, this);
                CallCtrlWithThreadSafety.SetText(lbMAF, PublicObject.CurTask.produceDate.ToString("yyyy-MM-dd"), this);
                CallCtrlWithThreadSafety.SetText(lbYXQ, PublicObject.CurTask.yxq.ToString("yyyy-MM-dd"), this);

                CallCtrlWithThreadSafety.SetText(lbQty1, PublicObject.arrCode1.Count.ToString(), this);
                CallCtrlWithThreadSafety.SetText(lbQty2, PublicObject.arrCode2.Count.ToString(), this);
                CallCtrlWithThreadSafety.SetText(lbQty3, PublicObject.arrCode3.Count.ToString(), this);
                CallCtrlWithThreadSafety.SetText(lbQty4, PublicObject.arrCode4.Count.ToString(), this);

                CallCtrlWithThreadSafety.SetText(lbPrintInfo, WorkSpace.GetInstance().GetPrintInfoString(), this);

                if (PublicObject.CodeValid.Count>0)
                {
                    CallCtrlWithThreadSafety.SetText(lbDupCheckInfo, PublicObject.CodeValid.Count.ToString(), this);
                    CallCtrlWithThreadSafety.SetText(lbDupCheckTip, "数据源查重", this);
                }
                else
                {
                    CallCtrlWithThreadSafety.SetText(lbDupCheckInfo, PublicObject.CodeScanned.Count.ToString(), this);
                    CallCtrlWithThreadSafety.SetText(lbDupCheckTip, "历史查重", this);
                }
                


                CallCtrlWithThreadSafety.SetVisible(btnRun, true, this);
                CallCtrlWithThreadSafety.SetVisible(btnInStatus, true, this);
                CallCtrlWithThreadSafety.SetVisible(btnExport, true, this);

                CallCtrlWithThreadSafety.SetText(btnRun, "暂停任务", this);

                numLogCLrPeriod = ConfigurationHelper.AppGetInt("logClrPeriod");
                numProccessCLrPeriod = ConfigurationHelper.AppGetInt("proccessCLrPeriod");
                numSaveTimeSpan = ConfigurationHelper.AppGetInt("autoSaveTimeSpan");//自动保存数据时间间隔，每次启动更新
                if (numSaveTimeSpan<=4)
                {
                    numSaveTimeSpan = 5;
                }

                lastSaveQty = 0;

                //frmError.ClearInfo();
            });

            WorkSpace.GetInstance().TaskFinishEvent += new EventHandler<EventArgs>((s1, s2) =>
            {
                CallCtrlWithThreadSafety.SetText(lbTYM, "", this);
                CallCtrlWithThreadSafety.SetText(lbPZWH, "", this);
                CallCtrlWithThreadSafety.SetText(lbBatch, "", this);
                CallCtrlWithThreadSafety.SetText(lbCreator, "", this);
                CallCtrlWithThreadSafety.SetText(lbLine, "", this);

                CallCtrlWithThreadSafety.SetText(lbTaskID, "", this);
                CallCtrlWithThreadSafety.SetText(lbGG, "", this);
                CallCtrlWithThreadSafety.SetText(lbRatio,"", this);
                CallCtrlWithThreadSafety.SetText(lbMAF, "", this);
                CallCtrlWithThreadSafety.SetText(lbYXQ, "", this);

                CallCtrlWithThreadSafety.SetText(lbQty1, "0", this);
                CallCtrlWithThreadSafety.SetText(lbQty2, "0", this);
                CallCtrlWithThreadSafety.SetText(lbQty3, "0", this);
                CallCtrlWithThreadSafety.SetText(lbQty4, "0", this);

                CallCtrlWithThreadSafety.SetText(lbPrintInfo, "", this);
                CallCtrlWithThreadSafety.SetText(lbDupCheckInfo, "0", this);
                CallCtrlWithThreadSafety.SetText(lbDupCheckTip, "查重信息", this);

                CallCtrlWithThreadSafety.SetVisible(btnRun, false, this);
                CallCtrlWithThreadSafety.SetVisible(btnInStatus, false, this);
                CallCtrlWithThreadSafety.SetVisible(btnExport, false, this);
                    
                //frmError.ClearInfo();

                lastRltCodeLoadTime = DateTime.MinValue;
            });


            WorkSpace.GetInstance().CodeSaveEvent += new EventHandler<Utility.Extend.CodeSaveEventArg>((s1, s2) => 
            {
                if (s2==null || s2.CodeQtyChanged)
                {
                    CallCtrlWithThreadSafety.SetText(lbQty1, PublicObject.arrCode1.Count.ToString(), this);
                    CallCtrlWithThreadSafety.SetText(lbQty2, PublicObject.arrCode2.Count.ToString(), this);
                    CallCtrlWithThreadSafety.SetText(lbQty3, PublicObject.arrCode3.Count.ToString(), this);
                    CallCtrlWithThreadSafety.SetText(lbQty4, PublicObject.arrCode4.Count.ToString(), this);

                }

                if (frmCurrent.Name.Equals("FrmWarehourseInStatus"))
                {//正处于任务信息窗口，刷新显示
                    if (this.CodeSaveEvent != null && frmCurrent.IsInit())
                    {
                        this.CodeSaveEvent(s1, s2);
                    }
                }
            });

            WorkSpace.GetInstance().CodePrintEvent += new EventHandler<Utility.Extend.CodePrintEventArg>((s1, s2) =>
            {
                CallCtrlWithThreadSafety.SetText(lbQty2, PublicObject.arrCode2.Count.ToString(), this);
                CallCtrlWithThreadSafety.SetText(lbQty3, PublicObject.arrCode3.Count.ToString(), this);
                CallCtrlWithThreadSafety.SetText(lbQty4, PublicObject.arrCode4.Count.ToString(), this);

                CallCtrlWithThreadSafety.SetText(lbPrintInfo, WorkSpace.GetInstance().GetPrintInfoString(), this);

                if (frmCurrent.Name.Equals("WarehourseInStatus") && frmCurrent.IsInit())
                {//正处于任务信息窗口，刷新显示
                    if (this.CodePrintEvent != null)
                    {
                        this.CodePrintEvent(s1, s2);
                    }
                }
            });

            WorkSpace.GetInstance().TaskPauseEvent += new EventHandler<EventArgs>((s1, s2)=>
            {
                CallCtrlWithThreadSafety.SetColor(btnRun, Color.Red, this);
                CallCtrlWithThreadSafety.SetText(btnRun, "启动任务", this);  

            });

            WorkSpace.GetInstance().TaskResumeEvent += new EventHandler<EventArgs>((s1, s2) =>
            {
                CallCtrlWithThreadSafety.SetColor(btnRun, Color.Green, this);
                CallCtrlWithThreadSafety.SetText(btnRun, "暂停任务", this);  
            });

            WorkSpace.GetInstance().CodeRefreshEvent += new EventHandler<EventArgs>((s1, s2) =>
            {
                CallCtrlWithThreadSafety.SetText(lbQty1, PublicObject.arrCode1.Count.ToString(), this);
                CallCtrlWithThreadSafety.SetText(lbQty2, PublicObject.arrCode2.Count.ToString(), this);
                CallCtrlWithThreadSafety.SetText(lbQty3, PublicObject.arrCode3.Count.ToString(), this);
                CallCtrlWithThreadSafety.SetText(lbQty4, PublicObject.arrCode4.Count.ToString(), this);

                if (frmCurrent.Name.Equals("FrmWarehourseInStatus"))
                {//正处于任务信息窗口，刷新显示
                    if (this.CodeRefreshEvent != null)
                    {
                        this.CodeRefreshEvent(s1, s2);
                    }
                }
            });

            WorkSpace.GetInstance().CriticalErrorEvent += new EventHandler<EventArgs>((s1, s2) => 
            {

                //frmError.AppendLog(WorkSpace.GetInstance().ErrorString);
                //if (!frmError.Visible)
                //{
                //    frmError.Show();
                //}

                msgErr.Add(WorkSpace.GetInstance().ErrorString);

                //chkForce.Visible = true;

            });
            WorkSpace.GetInstance().StartupPath = Application.StartupPath;

            tempDir = Application.StartupPath + "\\tmp";
            if (!Directory.Exists(tempDir))
            {
                Directory.CreateDirectory(tempDir);
            }

            logDir = Application.StartupPath + "\\log";
            if (!Directory.Exists(logDir))
            {
                Directory.CreateDirectory(logDir);
            }

            expDir = Application.StartupPath + "\\exception";
            if (!Directory.Exists(expDir))
            {
                Directory.CreateDirectory(expDir);
            }

            #endregion
            panelTip.BackColor = Color.FromArgb(213, 229, 244);

            #region 设置状态栏文本
            slbTip.Text = "当前用户：" + PublicObject.CurUser.loginName;
            string product = (Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyProductAttribute), false)[0] as AssemblyProductAttribute).Product;
            string ver = string.Format(" V{0}.{1}.{2}", Assembly.GetExecutingAssembly().GetName().Version.Major, Assembly.GetExecutingAssembly().GetName().Version.Minor, Assembly.GetExecutingAssembly().GetName().Version.Build);
            string company = (Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCompanyAttribute), false)[0] as AssemblyCompanyAttribute).Company;
            string copyright = (Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false)[0] as AssemblyCopyrightAttribute).Copyright;

            slbCompany.Text = string.Format("{0} {1}", company, copyright);
            this.Text = string.Format("{0} {1}", product, ver);

            slbDate.Text = DateTime.Now.ToString("yyyy-MM-dd ") + System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetDayName(DateTime.Now.DayOfWeek); ;
            #endregion

            //取消登录窗口后，使用默认用户
            msg = string.Empty;
            //PublicObject.CurUser = DALOpr.QuerySingle<User>(ref msg);
            //PublicObject.CurCompany = DALOpr.QuerySingle<CompanyInfo>(ref msg);

            #region 测试

            //int ratio = AppHelper.GetStationRatio2(3, "1:60:600");//获取顶级码相对扫描码的包装比值
            //Debug.WriteLine(ratio);

            //ratio = AppHelper.GetStationRatio2(3, "1:6:60:600");//获取顶级码相对扫描码的包装比值
            //Debug.WriteLine(ratio);

            //正则表达式
            //string code = "201409120000200004850378，禽流感二价灭活疫苗（H5N1 Re-6株+H9N2 Re-2株），兽药生字（2012）190022193，肇庆大华农，07583625398";

            //if (ValidateHelper.IsMatch(code, ConfigurationHelper.AppGetString("codeReg")))
            //{
            //    Console.WriteLine("\r\n匹配：{0}", ValidateHelper.Match(code, ConfigurationHelper.AppGetString("codeReg")));
            //}
            //else
            //{
            //    Console.WriteLine("\r\n不匹配");
            //}

            //测试浅复制
            //List<CodeInfo> ints = new List<CodeInfo>();

            //CodeInfo info = new CodeInfo();
            //CodeInfo info2;
            //info.code = "1811041531001";
            //info.serialNumber2 = 1;
            //ints.Add(info);

            //info2 = info.Clone() as CodeInfo;
            //info2.code = "1811041531002";
            //info2.serialNumber2 = 2;
            //ints.Add(info2);

            //info2 = info.Clone() as CodeInfo;
            //info2.code = "1811041531003";
            //info2.serialNumber2 = 3;
            //ints.Add(info2);

            //测试互换和二次扫描排序
            //info = new CodeInfo();
            //info.code = "1811041531003";
            //info.serialNumber2 = 3;
            //ints.Add(info);

            //info = new CodeInfo();
            //info.code = "1811041531004";
            //info.serialNumber2 = 4;
            //ints.Add(info);

            //info = new CodeInfo();
            //info.code = "1811041531002";
            //info.serialNumber2 = 2;
            //ints.Add(info);

            //List<CodeInfo> infos = ints.OrderBy(x => x.serialNumber2).ToList();
            //info = infos[3];

            ////互换
            //string tmp = info.code;
            //info.code = infos[2].code;
            //infos[2].code = tmp;

            //测试品名和文号提取
            //string s = "我是中国abc人";
            //int len = s.Length;

            //Console.WriteLine(len);

            //s = "201409120000200004850378,禽流感二价灭活疫苗（H5N1 Re-6株，H9N2 Re-2株），兽药生字（2012）190022193，肇庆大华农，07583625398";
            //string tym = AppHelper.SYZSGetTym(s);
            //string pzwh = AppHelper.SYZSGetPZWH(s);

            //Console.WriteLine(tym+",,,,,"+pzwh);

            //批量添加

            //List<CodeInfo> codes = new List<CodeInfo>();
            //CodeInfo code;
            //msg = string.Empty;


            //for (int i = 0; i < 20000; i++)
            //{
            //    code = new CodeInfo();
            //    code.sourceID = 0;
            //    code.code = i.ToString("D24");
            //    code.inTime = DateTime.Now;
            //    code.codeState = 1;

            //    codes.Add(code);
            //}

            //List<Dictionary<string, object>> ld = EntityHelper.GetDicDatas(codes);
            //DataTable dt = ld.ToDataTable();
            //dt.TableName = "CodeInfo";
            //bool b = DALOpr.ExcuteBulkCopy("CodeInfo", dt, ref msg);
            //if (!b)
            //{
            //    Console.WriteLine(msg);
            //}

            //int i1 = AppHelper.GetStationRatio(1, "1:2:8:64");
            //int i2 = AppHelper.GetStationRatio(2, "1:2:8:64");
            //int i3 = AppHelper.GetStationRatio(3, "1:2:8:64");
            //int i4 = AppHelper.GetStationRatio(4, "1:2:8:64");

            //int j1 = AppHelper.GetStationRatio2(1, "1:2:8:64");
            //int j2 = AppHelper.GetStationRatio2(2, "1:2:8:64");
            //int j3 = AppHelper.GetStationRatio2(3, "1:2:8:64");
            //int j4 = AppHelper.GetStationRatio2(4, "1:2:8:64");

            //Encoding enc = FileUtil.GetEncoding(@"C:\Users\conno\Desktop\t\gbk.txt");
            //Console.WriteLine(enc.BodyName);
            //enc = FileUtil.GetEncoding(@"C:\Users\conno\Desktop\t\utf-8.txt");
            //Console.WriteLine(enc.BodyName);
            //enc = FileUtil.GetEncoding(@"C:\Users\conno\Desktop\t\三级码.txt");
            //Console.WriteLine(enc.BodyName);

            //DALOpr.UpdateRltData(new List<string>(new string[] { "6467567", "134234", "0890890"}), "123", ref msg);

            #endregion

            treeView1.Nodes[0].Expand();
            treeView1.Nodes[0].Nodes[0].Expand();

            FrmFirstPage frm = new FrmFirstPage();
            panelForm.Controls.Add(frm);
            frmCurrent = frm;

            frm.Show();

            timer1.Start();
            bInit = true;
        }

        #region 切换窗体

        public void SwtichForm(FrmBase f)
        {
            if (f == null)
            {
                return;
            }

            //判断是否允许切换
            if (WorkSpace.GetInstance().IfTaskFree())
            {
                if (f.GetType().FullName.Contains("WarerHourseIn"))
                {
                    MessageBox.Show("当前无生产任务，无法进入【关联入库】模块！");
                    return;
                }
            }
            else
            {
                //允许进入，但是不允许再次运行
                //if (f.GetType().FullName.Contains("TaskRun"))
                //{
                //    MessageBox.Show("当前生产任务正忙，无法进入【派发任务】模块！");
                //    return;
                //}
            }

            if (frmCurrent == null)
            {
                panelForm.Controls.Clear();
                panelForm.Controls.Add(f);
                frmCurrent = f;

                f.Show();
            }
            else
            {

                if (!panelForm.Controls.Contains(f))
                {
                    frmCurrent.Hide();
                    frmCurrent.Close();
                    //foreach (Control ctrl in panelForm.Controls)
                    //{
                    //    if (ctrl is FrmBase)
                    //    {
                    //        ctrl.Hide();
                    //        (ctrl as FrmBase).Close();
                    //        break;
                    //    }
                        
                    //}

                    panelForm.Controls.Clear();
                    panelForm.Controls.Add(f);
                    frmCurrent = f;
                    f.Show();
                }
            }
        }

        public void SwitchFormByModuleName(string name, params object[] tag)
        {
            TreeNode node = FindNodeByName(name, treeView1.Nodes);
            if (node == null)
            {
                return;
            }

            if (frmCurrent != null && frmCurrent.Name.Equals("Frm" + node.Name))
            {//当前窗口就是本节点对应窗口
                return;
            }

            //SwitchFormByNode(node);
            FrmBase obj = Assembly.GetExecutingAssembly().CreateInstance("UniRlv.UI.Main." + node.Parent.Name + ".Frm" + node.Name, true) as FrmBase;

            if (tag != null && tag.Length > 0)
            {
                obj.Tag = tag[0];
            }

            lbCaption.Text = "入库系统>>>" + node.Parent.Text + ">>>" + node.Text;
            picCaption.Image = imgList32.Images[node.ImageIndex];
            SwtichForm(obj);

            node.Parent.Expand();
        }

        private TreeNode FindNodeByName(string name, TreeNodeCollection nodes)
        {
            foreach (TreeNode item in nodes)
            {
                if (item.Name.Equals(name, StringComparison.OrdinalIgnoreCase))
                {
                    return item;
                }
                else
                {
                    TreeNode node = FindNodeByName(name, item.Nodes);
                    if (node != null)
                    {
                        return node;
                    }
                }
            }

            return null;
        }

        private void SwitchFormByNode(TreeNode node)
        {
            if (frmCurrent != null && frmCurrent.Name.Equals("Frm" + node.Name))
            {//当前窗口就是本节点对应窗口
                return;
            }

            try
            {

                object obj = Assembly.GetExecutingAssembly().CreateInstance("UniRlv.UI.Main." + node.Parent.Name + ".Frm" + node.Name, true);

                lbCaption.Text = "入库系统>>>" + node.Parent.Text + ">>>" + node.Text;
                picCaption.Image = imgList32.Images[node.ImageIndex];
                SwtichForm(obj as FrmBase);
            }
            catch (Exception exp)
            {
                MessageBox.Show(this, exp.Message, "出现异常", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

        }

        private void treeView1_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            TreeNode node = e.Node;
            
            if (node.Nodes == null || node.Nodes.Count == 0)
            {//最底层节点
                if (node.Name == "About")
                {
                    AboutBox frm = new AboutBox();

                    frm.ShowDialog();
                    return;
                }

                if (node.Tag==null || node.Tag.ToString().Length == 0)
                {
                    //反射
                    SwitchFormByNode(node);
                }
                else
                {
                    System.Diagnostics.ProcessStartInfo Info = new System.Diagnostics.ProcessStartInfo();
                    Info.FileName = node.Tag.ToString();//"calc.exe"为计算器，"notepad.exe"为记事本

                    try
                    {
                        System.Diagnostics.Process Proc = System.Diagnostics.Process.Start(Info);
                    }
                    catch (Exception)
                    {

                    }
                    
                }
            }
        }

        #endregion


        private void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e)
        {
            
            TreeNode root = treeView1.Nodes[0];
            foreach (TreeNode item in root.Nodes)
            {
                if (item.IsExpanded)
                {
                    item.Collapse();
                }

            }

            if (e.Node.Name.Contains("SystemManage"))
            {//需要输入密码
                FrmPwdVerify frm = new FrmPwdVerify();
                DialogResult dr = frm.ShowDialog();
                if (dr == DialogResult.No)
                {
                    e.Cancel = true;
                    MessageBox.Show("密码错误，无法进入该模块！");
                    return;
                }
                else if (dr == DialogResult.Cancel)
                {
                    e.Cancel = true;
                    return;
                }
            }
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (!e.Node.IsExpanded)
            {
                e.Node.Expand();
            }
        }

        private void btnRun_Click(object sender, EventArgs e)
        {
            if (btnRun.Text == "启动任务")
            {
                WorkSpace.GetInstance().ResumeTask();
            }
            else
            {
                WorkSpace.GetInstance().PauseTask();
            }
        }

        private void btnInStatus_Click(object sender, EventArgs e)
        {
            SwitchFormByModuleName("WarehourseInStatus");
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            SwitchFormByModuleName("DataDeal");
        }

        public string GetErrorMsg()
        {
            if (msgErr.Count>0)
            {
                string s = msgErr[0];
                msgErr.RemoveAt(0);

                return s;
            }
            else
            {
                return "";
            }
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (msgErr.Count > 0)
            {
                //    frmError.AppendLog(msgErr[0]);
                //    if (!frmError.Visible && !frmError.ForceHide)
                //    {
                //        frmError.Show();
                //    }
                if (CriticalError != null)
                {
                    CriticalError(this, null);
                    //msgErr.RemoveAt(0);
                }
                
            }


            ticksSystem++;

            if ((ticksSystem * timer1.Interval) % 60000 == 0)
            { //一分钟一次
                ThreadPool.QueueUserWorkItem(new WaitCallback(s=> 
                {

                    //删除旧文件
                    IEnumerable<string> files = Directory.EnumerateFiles(tempDir, "*.xml", SearchOption.TopDirectoryOnly);
                    FileInfo fi;
                    TimeSpan ts;
                    foreach (var item in files)
                    {
                        fi = new FileInfo(item);
                        ts = DateTime.Now - fi.CreationTime;

                        if (ts.Days > numProccessCLrPeriod)
                        {//临时文件大于numProccessCLrPeriod天，自动删除
                            try
                            {
                                File.Delete(item);
                            }
                            catch (Exception)
                            {

                            }

                        }
                    }

                    files = Directory.EnumerateFiles(expDir, "*.txt", SearchOption.TopDirectoryOnly);

                    foreach (var item in files)
                    {
                        fi = new FileInfo(item);
                        ts = DateTime.Now - fi.CreationTime;

                        if (ts.Days > numLogCLrPeriod)
                        {//异常文件大于x天，自动删除
                            try
                            {
                                File.Delete(item);
                            }
                            catch (Exception)
                            {

                            }

                        }
                    }

                    files = Directory.EnumerateFiles(logDir, "*.log", SearchOption.TopDirectoryOnly);

                    foreach (var item in files)
                    {
                        fi = new FileInfo(item);
                        ts = DateTime.Now - fi.CreationTime;

                        if (ts.Days > numLogCLrPeriod)
                        {//日志文件大于x天，自动删除
                            try
                            {
                                File.Delete(item);
                            }
                            catch (Exception)
                            {

                            }

                        }
                    }

                }));
            }

            if (PublicObject.CurTask!=null && PublicObject.CurTask.state == (int)task_state.TS_RUN)
            {
                if ((ticksSystem*timer1.Interval) % (numSaveTimeSpan*1000) == 0)
                {
                    Debug.WriteLine("time to auto save!");

                    if (PublicObject.arrCode1.Count != lastSaveQty)
                    {//数量有变化，自动保存
                        ThreadPool.QueueUserWorkItem(new WaitCallback((s)=> 
                        {
                            Debug.WriteLine("qty changed, auto save!");

                            string path = string.Format("{3}\\进度文件_{0}_批次{1}_任务号{4}_{2}.xml", PublicObject.CurProduct.tym , PublicObject.CurTask.batch, DateTime.Now.ToString("yyyyMMdd_HHmmss"), tempDir, PublicObject.CurTask.ID);

                            try
                            {
                                if (FrmDataDeal.ExportScanProccess(path))
                                {
                                    lastSaveQty = PublicObject.arrCode1.Count;

                                    //删除更早前的进度文件
                                    IEnumerable<string> files = Directory.EnumerateFiles(tempDir, "*.xml", SearchOption.TopDirectoryOnly);

                                    FileInfo fi;
                                    foreach (var item in files)
                                    {
                                        fi = new FileInfo(item);

                                        TimeSpan ts = DateTime.Now - fi.CreationTime;
                                        if (ts.TotalMinutes > 10)
                                        {//4个小时之前的  //2020-03-25，单位改为分钟，删除10分钟之前的

                                            File.Delete(item);
     
                                        }
                                    }
                                }
                            }
                            catch (Exception exp)
                            {
                                Program.AppendExceptionLog("导出进度文件失败：" + exp.ToString());
                            }

                        }), ticksSystem);
                    }

                    Debug.WriteLine("time to load rlt code!");


                    //加载关联数据
                    DateTime nowTime = DateTime.Now.AddSeconds(-60);//只加载一分钟前的数据，担心最新数据会被修改
                    string msg = string.Empty;
                    string whereString;

                    if (lastRltCodeLoadTime == DateTime.MinValue)
                    {
                        PublicObject.CodeRlt.Clear();

                        whereString = $" batch='{PublicObject.CurTask.batch}' and codeState=0 and inTime<='{nowTime.ToString("yyyy-MM-dd HH:mm:ss.000")}'";

                    }
                    else
                    {
                        whereString = $" batch='{PublicObject.CurTask.batch}' and codeState=0 and inTime<='{nowTime.ToString("yyyy-MM-dd HH:mm:ss.000")}' and inTime>'{lastRltCodeLoadTime.AddSeconds(-1).ToString("yyyy-MM-dd HH:mm:ss.000")}'";
                    }

                    List<CodeRltInfo> rss = DALOpr.Query<CodeRltInfo>(whereString, ref msg);

                    if (rss != null && rss.Count > 0)
                    {
                        foreach (var item in rss)
                        {
                            if (!PublicObject.CodeRlt.Contains(item))
                            {
                                PublicObject.CodeRlt.Add(item);
                            }
                        }

                        Debug.WriteLine("load rlt codes:" + rss.Count);
                    }

                    lastRltCodeLoadTime = nowTime;
                }
            }
        }

        private void btnTest_Click(object sender, EventArgs e)
        {
            //string msg = "";
            //bool bRes = WorkSpace.GetInstance().PrintTwoLabels(3, 4, false, ref msg);
            //MessageBox.Show(bRes.ToString());

            msgErr.Add("测试错误：2222");
        }

        private void chkForce_CheckedChanged(object sender, EventArgs e)
        {
            //frmError.ForceHide = chkForce.Checked;

            //if (chkForce.Checked)
            //{
            //    if (frmError.Visible)
            //    {
            //        frmError.Close();
            //    }
            //}
            //else
            //{
            //    if (msgErr.Count == 0)
            //    {
            //        chkForce.Visible = false;
            //    }
            //}
        }
    }
}
